<template>
  <div class="content">
    <el-form label-width="80px">
      <el-form-item :label="messages.multiple">
        <el-switch v-model="allowMultipleChoice" @change="setAllowMultipleChoice"></el-switch>
        <span class="help-inline">{{ messages.tip_multiple }}</span>
      </el-form-item>
      <el-form-item :label="messages.refresh">
        <el-switch v-model="autoRefresh" @change="setAutoRefresh"></el-switch>
        <span class="help-inline">{{ messages.tip_refresh }}</span>
      </el-form-item>
      <el-form-item label="Port">{{ server.port }}</el-form-item>
      <el-form-item label="IPv4">
        <div v-for="item in ipv4" class="copy-list">
          <div class="text">{{ item }}</div>
          <span class="btn-copy" :data-clipboard-text="item">
            <el-icon><DocumentCopy/></el-icon>
          </span>
        </div>
      </el-form-item>
      <el-form-item>
        <a @click="emit('change-proxy')" target="_blank" class="link">{{ messages.change_proxy_service }}</a>
      </el-form-item>
      <el-form-item>
        <a @click="handleSetShortcut" target="_blank" class="link">{{ messages.shortcut }}</a>
      </el-form-item>
      <el-form-item>
        <a v-bind:href="apiUrl" target="_blank" class="link">
          {{ messages.moreSettings }}</a>
      </el-form-item>
    </el-form>
  </div>

</template>

<script setup>
import {messages} from '../uses/useI18nMessage.js';
import {allowMultipleChoice, autoRefresh, server, apiUrl, init} from '../uses/useInit.js';
import {computed, onMounted, ref} from 'vue';
import Clipboard from 'clipboard';
import {DocumentCopy} from '@element-plus/icons-vue';
import {bStorage, bService, bContextMenu} from '../api';

const setAllowMultipleChoice = async (value) => {
  await bService.setAllowMultipleChoice(value);
  await init();
  await bContextMenu.setMenu();
};
const setAutoRefresh = () => {
  bStorage.set('auto-refresh', autoRefresh.value);
  bContextMenu.setMenu();
};

const ipv4 = computed(() => {
  try {
    const url = new URL(apiUrl.value);
    if (!['127.0.0.1', 'localhost'].includes(url.hostname)) {
      return [url.hostname];
    }
  } catch (e) {
  }
  return server.value.ipv4;
});

const emit = defineEmits(['change-proxy']);
const handleSetShortcut = () => {
  chrome.tabs.create({url: 'chrome://extensions/shortcuts'});
};
onMounted(() => {
  new Clipboard('.btn-copy');
});
</script>

<style scoped lang="scss">
.copy-list {
  display: flex;
  align-items: center;
  border-bottom: 1px dashed #efefef;


  .text {
    flex: 1;
  }

  .btn-copy {
    cursor: pointer;
    color: #409EFF;
    margin-left: 5px;

    i:first-child {
      transform: translate(15px, -2px);
    }

    i:last-child {
      background: #ffffff;
      transform: translate(-2px, 1px);
    }
  }
}

</style>
